package cn.itcast.aop;

import cn.itcast.pojo.Emp;
import cn.itcast.pojo.EmpLoginLog;
import cn.itcast.pojo.LoginInfo;
import cn.itcast.pojo.Result;
import cn.itcast.service.EmpLoginLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Aspect
@Component
public class EmpLoginLogAspect {
    @Autowired
    private EmpLoginLogService empLoginLogService;

    @Around("execution(* cn.itcast.controller.LoginController.login(*))")
    public Object recordEmpLoginLog(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取运行参数
        Object[] args = joinPoint.getArgs();
        Emp empLogin = (Emp)args[0];//登录方法的参数是Emp对象

        //1.获取用户名
        String username = empLogin.getUsername();
        //2.获取输入的密码
        String password = empLogin.getPassword();

        //3.初始化日志对象
        EmpLoginLog empLoginLog = EmpLoginLog.builder().username(username)
                .password(password)
                .loginTime(LocalDateTime.now())
                .isSuccess((short)0)//默认失败
                .jwt(null)//默认无token
                .build();

        // 记录开始时间
        long start = System.currentTimeMillis();
        Object result = null;


        try {
            //调用方法（获取返回值）
            result = joinPoint.proceed(args);

            //如果正常返回，则判断是否登录成功
            if (result instanceof Result){
                Result loginResult = (Result) result;
                //判断是否登录成功
                if (loginResult.getCode()==1){
                    //登录成功
                    empLoginLog.setIsSuccess((short)1);
                    //获取jwt令牌
                    LoginInfo loginInfo = (LoginInfo)loginResult.getData();
                    String token = loginInfo.getToken();
                    empLoginLog.setJwt(token);
                }

            }
        } catch (Throwable e) {
            //抛出异常，说明初始化失败
            throw new RuntimeException(e);
        } finally {
            //设置执行时间  无论是否成功都执行
            empLoginLog.setCostTime(System.currentTimeMillis()-start);
            empLoginLogService.insert(empLoginLog);//插入日志
        }

        return result;

    }
}
